<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat BI 智能分析小助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入ECharts用于数据可视化 -->
    <script src="css/echarts.esm.min.js"></script>

    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-database text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">Chat BI 智能分析小助手</h1>
            </div>
            <nav class="hidden md:flex items-center space-x-6">
                <!-- 导航链接 -->
            </nav>
            <button class="md:hidden text-gray-600 focus:outline-none" id="menu-toggle">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden bg-white shadow-lg absolute w-full" id="mobile-menu">
            <div class="container mx-auto px-4 py-3 flex flex-col space-y-3">
                <!-- 移动端导航链接 -->
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="flex-grow container mx-auto px-4 py-6 md:py-10">
        <div class="max-w-4xl mx-auto">
            <!-- 欢迎信息 -->
            <div class="bg-gradient-to-r from-primary/90 to-secondary/90 rounded-xl p-6 md:p-8 shadow-lg mb-8 text-white transform hover:scale-[1.01] transition-transform duration-300">
                <h2 class="text-2xl md:text-3xl font-bold mb-3">欢迎使用 Chat BI 智能分析小助手</h2>
                <p class="text-lg md:text-xl opacity-90">我可以帮你分析数据库中的数据，并根据知识库回答相关问题。</p>
            </div>

            <!-- 聊天界面 -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden h-[600px] flex flex-col">
                <!-- 聊天历史 -->
                <div class="flex-grow overflow-y-auto p-4 scrollbar-hide" id="chat-history">
                    <!-- 系统消息 -->
                    <div class="flex items-start mb-4">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-primary flex items-center justify-center text-white">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div class="ml-3 max-w-[85%]">
                            <div class="bg-gray-100 rounded-lg p-4 shadow-sm">
                                <p class="text-gray-800">你好！我是Chat BI小助手，有什么可以帮助你的？请在下方输入你的问题。</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="border-t border-gray-200 p-4">
                    <div class="flex">
                        <input type="text" id="user-input" placeholder="请输入你的问题..." class="flex-grow rounded-l-lg border border-gray-300 py-2 px-4 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200">
                        <button id="send-button" class="bg-primary hover:bg-primary/90 text-white px-6 rounded-r-lg transition-colors duration-200 flex items-center justify-center">
                            <i class="fa fa-paper-plane mr-2"></i> 发送
                        </button>
                    </div>
                </div>
            </div>

            <!-- 思考过程展示 -->
            <div class="mt-6 bg-white rounded-xl shadow-lg p-4 md:p-6">
                <h3 class="text-xl font-semibold mb-3 flex items-center">
                    <i class="fa fa-lightbulb-o text-yellow-500 mr-2"></i>
                    思考过程
                </h3>
                <div id="thinking-process" class="text-sm text-gray-600 max-h-64 overflow-y-auto scrollbar-hide bg-gray-50 p-3 rounded-lg">
                    <p class="text-gray-500 italic">等待用户提问...</p>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4 text-center text-gray-500">
            <p>© 2025 Chat BI 智能分析小助手</p>
            <div class="mt-3 flex justify-center space-x-4">
                <a href="#" class="text-gray-400 hover:text-primary transition-colors duration-200">
                    <i class="fa fa-github text-xl"></i>
                </a>
                <a href="#" class="text-gray-400 hover:text-primary transition-colors duration-200">
                    <i class="fa fa-twitter text-xl"></i>
                </a>
                <a href="#" class="text-gray-400 hover:text-primary transition-colors duration-200">
                    <i class="fa fa-linkedin text-xl"></i>
                </a>
            </div>
        </div>
    </footer>

    <script>
        // 导航栏滚动效果
        window.addEventListener('scroll', function() {
            const navbar = document.getElementById('navbar');
            if (window.scrollY > 10) {
                navbar.classList.add('shadow-md', 'py-2');
                navbar.classList.remove('shadow-sm', 'py-3');
            } else {
                navbar.classList.add('shadow-sm', 'py-3');
                navbar.classList.remove('shadow-md', 'py-2');
            }
        });

        // 移动端菜单切换
        document.getElementById('menu-toggle').addEventListener('click', function() {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });

        // 聊天功能
        document.getElementById('send-button').addEventListener('click', sendMessage);
        document.getElementById('user-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        function sendMessage() {
            const userInput = document.getElementById('user-input');
            const message = userInput.value.trim();

            if (message === '') {
                return;
            }

            // 显示用户消息
            appendMessage('user', message);

            // 清空输入框
            userInput.value = '';

            // 显示加载状态
            appendMessage('loading', '思考中...');

            // 发送消息到API
            fetch('/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ question: message })
            })
            .then(response => response.json())
            .then(data => {
                // 移除加载状态
                removeLoadingMessage();

                if (data.status === 'success') {
                    // 显示回答
                    appendMessage('assistant', data.answer, data.chart_data);

                    // 显示思考过程
                    displayThinkingProcess(data.thoughts);
                } else {
                    // 显示错误消息
                    appendMessage('assistant', `出错了: ${data.message}`);
                }
            })
            .catch(error => {
                // 移除加载状态
                removeLoadingMessage();

                // 显示错误消息
                appendMessage('assistant', `网络错误: ${error.message}`);
            });
        }

        function appendMessage(sender, message, chartData = null) {
            const chatHistory = document.getElementById('chat-history');
            let messageHTML = '';

            if (sender === 'user') {
                messageHTML = `
                    <div class="flex items-start justify-end mb-4">
                        <div class="mr-3 max-w-[85%]">
                            <div class="bg-primary text-white rounded-lg p-4 shadow-sm">
                                <p>${message}</p>
                            </div>
                        </div>
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center">
                            <i class="fa fa-user text-gray-600"></i>
                        </div>
                    </div>
                `;
            } else if (sender === 'assistant') {
                let chartDiv = '';
                if (chartData) {
                    // 创建图表容器
                    const chartId = `chart-${Date.now()}`;
                    chartDiv = `<div class="mt-3 h-64" id="${chartId}"></div>`;

                    // 在消息添加到DOM后初始化图表
                    setTimeout(() => {
                        initChart(chartId, chartData);
                    }, 100);
                }

                messageHTML = `
                    <div class="flex items-start mb-4">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-primary flex items-center justify-center text-white">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div class="ml-3 max-w-[85%]">
                            <div class="bg-gray-100 rounded-lg p-4 shadow-sm">
                                <p>${message}</p>
                                ${chartDiv}
                            </div>
                        </div>
                    </div>
                `;
            } else if (sender === 'loading') {
                messageHTML = `
                    <div class="flex items-start mb-4">
                        <div class="flex-shrink-0 h-10 w-10 rounded-full bg-primary flex items-center justify-center text-white">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div class="ml-3 max-w-[85%]">
                            <div class="bg-gray-100 rounded-lg p-4 shadow-sm">
                                <p class="animate-pulse-slow">${message}</p>
                            </div>
                        </div>
                    </div>
                `;
            }

            chatHistory.insertAdjacentHTML('beforeend', messageHTML);

            // 滚动到底部
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function removeLoadingMessage() {
            const chatHistory = document.getElementById('chat-history');
            const loadingMessage = chatHistory.querySelector('.animate-pulse-slow');

            if (loadingMessage) {
                loadingMessage.closest('div.flex').remove();
            }
        }

        function displayThinkingProcess(thoughts) {
            const thinkingProcess = document.getElementById('thinking-process');
            let html = '';

            if (thoughts && thoughts.length > 0) {
                thoughts.forEach(thought => {
                    html += `<p class="mb-1">${thought}</p>`;
                });
            } else {
                html = '<p class="text-gray-500 italic">无思考过程记录</p>';
            }

            thinkingProcess.innerHTML = html;
        }

        function initChart(chartId, chartData) {
            // 确保ECharts库已加载
            if (!window.echarts) {
                console.error('ECharts库未加载');
                return;
            }

            // 获取图表容器
            const chartDom = document.getElementById(chartId);
            if (!chartDom) {
                console.error(`找不到图表容器: ${chartId}`);
                return;
            }

            // 初始化图表
            const myChart = echarts.init(chartDom);

            // 根据数据类型设置图表配置
            const options = {
                title: {
                    text: '数据可视化',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                legend: {
                    data: ['数据']
                },
                xAxis: {
                    type: 'category',
                    data: chartData.xAxis || []
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: '数据',
                    type: chartData.type || 'bar',
                    data: chartData.yAxis || []
                }]
            };

            // 使用配置项显示图表
            myChart.setOption(options);

            // 监听窗口大小变化，调整图表
            window.addEventListener('resize', () => {
                myChart.resize();
            });
        }
    </script>
</body>
</html>